package com.xszx.server.service;

import com.xszx.server.dto.Page;
import com.xszx.server.dto.RoleDto;
import com.xszx.server.entity.RoleResource;
import com.xszx.server.entity.RoleUser;
import com.xszx.server.mapper.RoleUserMapper;
import com.xszx.server.util.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleUserService {
    @Resource
    private RoleUserMapper roleUserMapper;

    /**
     * 获取分页列表
     * @param page
     * @return
     */
    public Page getAllRoleUsers(Page page){
        int pageNum = page.getPage();
        page.setPage((page.getPage()-1)*page.getSize());
        page.setList(roleUserMapper.findAll(page));
        page.setTotal(roleUserMapper.findCount());
        page.setPage(pageNum);
        return page;
    }

    /**
     * 新增或者删除信息
     * @param roleUser
     * @return
     */
    public String saveOrUpdate(RoleUser roleUser){
        if(StringUtils.isEmpty(roleUser.getId())){
            roleUser.setId(UuidUtil.getShortUuid());
            return (roleUserMapper.insert(roleUser)>0)?"添加成功":"添加失败";
        }else{
            return (roleUserMapper.updateByPrimaryKey(roleUser)>0)?"更新成功":"更新失败";
        }
    }
    /**
     * 新增角色用户信息
     * @param roleDto
     * @return
     */
    @Transactional
    public void saveUsers(RoleDto roleDto){
        //角色的id
        String roleId = roleDto.getId();
        //资源的ids
        List<String> userIds = roleDto.getUserIds();
        //删除当前角色的资源信息
        roleUserMapper.deleteByRoleId(roleId);
        //循环添加
        for (String userId : userIds) {
            roleUserMapper.insert(new RoleUser(UuidUtil.getShortUuid(),roleId,userId));
        }
    }

    /**
     * 根据角色eid查询用户id
     * @param roleId
     * @return
     */
    public List<String> getUsersByRoleId(String roleId){
        return roleUserMapper.findUsersByRoleId(roleId);
    }

    /**
     * 物理删除角色用户关联
     * @param id
     * @return
     */
    public int del(String id){
        return roleUserMapper.deleteByPrimaryKey(id);
    }
     /**
     * 获取单个角色用户关联
     * @return
     */
    public RoleUser getRoleUser(String id){
        return roleUserMapper.selectByPrimaryKey(id);
    }
}
